package controllers

import (
	"anban/service"
	"anban/utils/wechat"
	"fmt"
	"github.com/astaxie/beego"
	"net/url"
	"strings"
)

type BaseController struct {
	beego.Controller
}

func (c *BaseController) Prepare() {
	noLogin := map[string]string{
		"CommonController/GetFrontRegionListByParent": "1",
		"CommonController/GetFrontSchoolByDistrict": "1",
		"CommonController/GetFrontClassBySchool": "1",
		"CommonController/SendMobileMsg": "1",
		/*"IndexController/Register": "1",
		"IndexController/InviteRegister": "1",
		"IndexController/DoRegister": "1",
		"IndexController/Index": "1",
		"ClassController/Add": "1",
		"ClassController/DoAdd": "1",
		"HomeworkNoticeController/ShowList": "1",
		"HomeworkNoticeController/LoadMore": "1",
		"MeetingNoticeController/ShowList": "1",
		"MeetingNoticeController/LoadMore": "1",
		"SafeNoticeController/ShowList": "1",
		"SafeNoticeController/LoadMore": "1",
		"TempNoticeController/Index": "1",
		"TempNoticeController/ShowList": "1",
		"TempNoticeController/LoadMore": "1",
		"TempNoticeController/Detail": "1",
		"TempNoticeController/DetailLoadMore": "1",
		"SchoolBusNoticeController/ShowList": "1",
		"SchoolBusNoticeController/LoadMore": "1",
		"GradeNoticeController/ShowList": "1",
		"GradeNoticeController/LoadMore": "1",
		"CourseNoticeController/ShowList": "1",
		"CourseNoticeController/LoadMore": "1",
		"UserController/MyWallet": "1",
		"UserController/Index": "1",
		"UserController/Withdraw": "1",
		"UserController/WithdrawLoadMore": "1",
		"UserController/FamilyMember": "1",
		"UserController/ParentAddressBook": "1",
		"UserController/ParentAddressBookLoadMore": "1",
		"UserController/SchoolAddressBook": "1",
		"StudentController/ProtectMember": "1",
		"StudentController/AddProtectMember": "1",
		"FeedbackController/DoAdd": "1",*/
	}
	noCheck := map[string]string{
		"CommonController/GetFrontRegionListByParent": "1",
		"CommonController/GetFrontSchoolByDistrict": "1",
		"CommonController/GetFrontClassBySchool": "1",
		"IndexController/Register": "1",
		"IndexController/DoRegister": "1",
		"IndexController/InviteRegister": "1",
		"IndexController/DoInviteRegister": "1",
	}

	tUrl := c.Ctx.Input.URL()
	ctl, act := c.GetControllerAndAction()
	ctlAct := fmt.Sprintf("%s/%s", ctl, act)
	c.Data["curUrl"] = ctlAct

	if _, ok := noLogin[ctlAct]; !ok {
		userId := c.GetSession("userId")
		ticket := c.GetSession("ticket")
		if userId == nil {
			code := c.GetString("code")
			if len(code) <= 0 {
				domain := c.Ctx.Input.Domain()
				redirectUrl := fmt.Sprintf("https://%s%s", domain, tUrl)
				appId := beego.AppConfig.String("wechatappid")
				url := fmt.Sprintf("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo#wechat_redirect",
					appId, redirectUrl)
				c.Redirect(url, 302)
				return
			} else {
				wechatUserInfo := wechat.GetWechatUserInfoByCode(code)
				p := map[string]interface{}{}
				p["openId"] = wechatUserInfo.Openid
				p["convert"] = true
				user := service.GetUserInfo(p)

				if user.Id <= 0 {
					c.Ctx.WriteString("<h1>系统中不存在该用户</h1>")
					return
				}

				editInput := url.Values{
					"id": {fmt.Sprintf("%d", user.Id)},
					"nick_name": {wechatUserInfo.Nickname},
					"head_img_url": {wechatUserInfo.Headimgurl},
					"union_id": {wechatUserInfo.Unionid},
				}
				service.EditUser(editInput)

				c.SetSession("userId", user.Id)

				if _, ok := noCheck[ctlAct]; !ok {
					switch user.Identity {
					case 0:
						if strings.Contains(tUrl, "teacher") {
							c.Redirect(beego.URLFor("teacher.IndexController.Register"), 302)
						} else if strings.Contains(tUrl, "parent") {
							c.Redirect(beego.URLFor("parent.IndexController.Register"), 302)
						}
					case 1:
						if strings.Contains(tUrl, "teacher") {
							c.Redirect(beego.URLFor("teacher.IndexController.Register"), 302)
						}
					case 2:
						if strings.Contains(tUrl, "parent") {
							c.Redirect(beego.URLFor("parent.IndexController.Register"), 302)
						}
					}
				}

				if ticket == nil {
					sceneQrcodeRes := wechat.CreateSceneQrcode(fmt.Sprintf("inviteparent_%d", user.Id))
					ticket = sceneQrcodeRes.Ticket
					c.SetSession("ticket", ticket)
				}

				c.Data["ticket"] = ticket
				c.Data["loginUser"] = user
			}
		} else {
			p := map[string]interface{}{}
			p["id"] = userId
			p["convert"] = true
			user := service.GetUserInfo(p)

			if _, ok := noCheck[ctlAct]; !ok {
				switch user.Identity {
				case 0:
					if strings.Contains(tUrl, "teacher") {
						c.Redirect(beego.URLFor("teacher.IndexController.Register"), 302)
					} else if strings.Contains(tUrl, "parent") {
						c.Redirect(beego.URLFor("parent.IndexController.Register"), 302)
					}
				case 1:
					if strings.Contains(tUrl, "teacher") {
						c.Redirect(beego.URLFor("teacher.IndexController.Register"), 302)
					}
				case 2:
					if strings.Contains(tUrl, "parent") {
						c.Redirect(beego.URLFor("parent.IndexController.Register"), 302)
					}
				}
			}

			if ticket == nil {
				sceneQrcodeRes := wechat.CreateSceneQrcode(fmt.Sprintf("inviteparent_%d", user.Id))
				ticket = sceneQrcodeRes.Ticket
				c.SetSession("ticket", ticket)
			}

			c.Data["ticket"] = ticket
			c.Data["loginUser"] = user
		}
	}
}